package com.itheima.controller;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result ex (Exception e){
        log.error("发生未知异常", e);
        return Result.error("操作失败,请联系管理员");
    }


    @ExceptionHandler(RuntimeException.class)
    public Result ex(RuntimeException e){
        log.error("发生运行时异常", e);
        return Result.error(e.getMessage());
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public Result ex(DuplicateKeyException e){
        log.error("发生重复数据异常", e);
        String msg = e.getCause().getMessage();
        String [] split = msg.split("\\s");
        return Result.error(split[2]+"数据已存在");
    }

    public static void main(String[] args) {
        String s = "Duplicate entry 'admin' for key 'idx_username'";
        String [] split = s.split("\\s+");
        System.out.println(split[2]);
    }
}
